const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')//美化JSON
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const InitManager=require('./cors/init')
const catchError=require('./middlewares/exception') //全局错误导出 如服务器五百等问题
require('module-alias/register')//别名
const fs = require('fs')
// const path = require('path')
// const morgan = require('koa-morgan')//错误日记
//   // 线上环境
//   const logFileName = path.join(__dirname, 'logs', 'access.log')
//   const writeStream = fs.createWriteStream(logFileName, {
//     flags: 'a'
//   })
//   app.use(morgan('combined', {
//     stream: writeStream
//   }));
// error handler
onerror(app) 
//require('./models/user') 之前导入表格
// middlewares
app.use(catchError)
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
  extension: 'pug'
}))
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}m1111s`)
})

InitManager.initCore(app)



// routes
// app.use(index.routes(), index.allowedMethods())
// app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
